import Web3 from "web3";
import electionArtifact from "../../build/contracts/ElectionContract.json";

window.vm = new Vue({
  el: "#vue-root",
  data: {
      account: "",
      status: false,
      num: 0,
      reciever: "",
      isCreator: false,
      candidates: [],
      history: []
  },
  computed: {
    getStatus:function(){
      return this.status?"进行中":"未开始";
    }
  },
  methods:{
    delCandidate:function(name,index){
      App.delCandidate(name,index);
    },
    clear:function(){
      this.candidates=[];
      this.history=[];
      this.status = false;
      this.num = 0;
      this.reciever = "";
    }
  }
});

const App = {
  web3 : null,
  account : null,
  election : null,
  price: 1000000000000000000,




  start: async function() {
    const { web3 } = this;

      // get contract instance
      // console.log(electionArtifact.address);
      // this.election = new web3.eth.Contract(
      //   electionArtifact.abi,
      //   electionArtifact.address,
      // );
      const networkId = await web3.eth.net.getId();
      // console.log(networkId);
      const deployedNetwork = electionArtifact.networks[networkId];
      // console.log(deployedNetwork);
      this.election = new web3.eth.Contract(
        electionArtifact.abi,
        deployedNetwork.address,
      );

      // get accounts获取当前账户
      const accounts = await web3.eth.getAccounts();
      this.account = accounts[0];
      vm.account = this.account;
      // console.log(this.account);//可注释
      //获取当前账户投票对象
      this.getCurrentUserVote();
      this.load();
      
      /*
        这个方法体中下面的语句都用于测试
      */


      // this.vote('bobo');
      // this.buyTicket()

      this.isOwner();
      // this.addCandidate('haohao',2);
      // this.getCandidates();
      // this.delCandidate('bobo')
      setTimeout(() => {
        this.getLenOfCan();
        this.getCandidates();
      }, 1000);
      this.getVoters();
      // this.stopVote()
      // this.getCurrentUserVote();
      // console.log(await load().call());
      // console.log(this.buyTicket());
      // this.buyTicket();
      // this.addCandidate('bobo',2);
      // this.getCandidates();
      // console.log(this.vote('bobo'));
      // console.log(this.addCandidate('bobo',2));
  },
  //初始化
  load:async function(){
    const {load} = this.election.methods;
    await load().send({
      from:this.account,
      gas:3000000
      // value:1000000000000000000
    },function(err,transactionHash){
      //res为true或false bool类型
      console.log('load err:'+err);
      console.log('load transactionHash:'+transactionHash);
    });
  },
  //买票
  buyTicket: function(){
    let that = this;
    this.web3.eth.getBalance(this.account).then(function(balance){
      balance = that.web3.utils.fromWei(balance,'ether');
      console.log(balance);
      if(balance < 1){
        //提示余额不足
        alert('余额不足');
        return;
      }
      const {buyTicket} = that.election.methods;
      //调用合约方法 购票
      buyTicket().send({
        from:that.account,
        gasPrice:'1',
        gas:3000000,
        value:1000000000000000000
      },function(err,transactionHash){
        /*
          err 为null就是成功
          买两次的话，会打印出err：Can not buy twice!
         */
        if(!err){
          alert("购买成功");
          vm.num = 1;
        }else{
          if(err.message.endsWith("Can not buy twice!")){
            alert("一人只能购买一票");
          }
        }
      });
    });
  },

  //参数为候选人姓名，会报错
  vote: function(){
    let name = document.getElementById("reciever").value;
    if(name=="" || name==null){
      alert("请选择投票对象");
      return;
    }
    const {vote} = this.election.methods;
    //调用合约方法 投票
    vote(name).send({
      from:this.account,
      gas:3000000
      // value:1000000000000000000
    },function(err,transactionHash){
      //res为true或false bool类型
      if(!err){
        alert("投票成功");
        vm.reciever = "name";
        vm.num = 0;
      }
      console.log('vote err:'+err);
      console.log('vote transactionHash:'+transactionHash);
    });
  },
  //参数：姓名，初始票数
  /*
    未考虑删除候选人，又再将其添加的情况
  */
  addCandidate: function(){
    let name = document.getElementById("nameInput").value.trim();
    if(name==""){
      alert("名字不能为空");
      return;
    }
    let alreadyAdd = false;
    let that = this;
    const{addCandidate} = this.election.methods;
    const{getCandidates} = this.election.methods;
    //调用合约方法，先getCandidate,判断是否已经添加
    getCandidates().call(function(err,res){
      for(let i=0; i<res.length; i++){
        // console.log(res.name)
        if(res[i].name === name && res[i].valid === true){
          //提示已经添加了该候选人
          alert('已经添加了'+name+'!');
          alreadyAdd = true;
          break;
        }
      }
      console.log(res);
      console.log('getCandidates err:' + err);
      //如果此候选人未被添加，则调用addCandidate
      if(!alreadyAdd){
        addCandidate(name, 0).send({
          from:that.account,
          gas:1000000,
        },function(err,transactionHash){
          if(!err){
            vm.candidates.push({
              name:name,
              tickets:0
            });
          }
          console.log('addCandidate transactionHash:'+ transactionHash);
          console.log('addCandidate err:'+ err);
          // App.getCandidates();
        });
      }
    })
    
  },
  //只是将有效值设置为false
  delCandidate: function(name,index){
    const{delCandidate} = this.election.methods;
    delCandidate(name).send({
      from:this.account,
      gas:1000000,
    },function(err,transactionHash){
      if(!err){
        vm.candidates.splice(index,1);
        alert("去除资格成功");
      }
      console.log('delCandidate transactionHash:' + transactionHash);
      console.log('delCandidate err:' + err);
    });
  },
  //要注意有效值为true的时候才有效
  getCandidates: function(){
    console.log("获取候选人列表");
    const{getCandidates} = this.election.methods;
    getCandidates().call(function(err,res){
      vm.candidates = [];
      //选出有效位为true的候选人，放入candidates数组中
      for(let i=0; i<res.length; i++){
        if(res[i].valid === true){
          vm.candidates.push({
            name:res[i].name,
            tickets:res[i].votes
          });
        }
      }
      // console.log(candidates);
      // console.log('getCandidates err:' + err);
    })
  },
  // 得到投票记录
  getVoters: function(){
    const{getVoters} = this.election.methods;
    getVoters().call(function(err, res){
      console.log(res);
      console.log('getVoters err:' + err);
    });
  },
  //得到当前账户的投票记录
  getCurrentUserVote: function(){
    const{getCurrentUserVote} = this.election.methods;
    getCurrentUserVote().call(function(err, res){
      vm.reciever = res.name||"";
      console.log('getCurrentUserVote err:',res);
      console.log('getCurrentUserVote err:' + err);
    })
  },
  
  //暂停投票 vote()方法报错，无法测试此方法
  suspendVote: function(){
    const{suspendVote} = this.election.methods;
    suspendVote().send({
      from:this.account,
      gas:1000000,
    },function(err,transactionHash){
      if(!err){
        vm.status = false;
        alert("暂停成功");
      }
      console.log('suspendVote transactionHash:'+ transactionHash);
      console.log('suspendVote err:'+ err);
    })
  },
  //开始投票 vote()方法报错，无法测试此方法
  startVote: function(){
    const{startVote} = this.election.methods;
    startVote().send({
      from:this.account,
      gas:1000000,
    },function(err,transactionHash){
      if(!err){
        vm.status = true;
        alert("开始成功");
      }
      console.log('startVote transactionHash:'+ transactionHash);
      console.log('startVote err:'+ err);
    })
  },
  //停止投票 这个测试了，可以清空一些数据
  stopVote: function(){
    let yes = confirm("确定终止投票？");
    if(!yes){
      return;
    }
    const{stopVote} = this.election.methods;
    stopVote().send({
      from:this.account,
      gas:1000000,
    },function(err,transactionHash){
      if(!err){
        vm.clear();
        alert("终止成功");
      }
      console.log('stopVote transactionHash:'+ transactionHash);
      console.log('stopVote err:'+ err);
    })
  },
  //新建投票 vote()方法报错，无法测试此方法
  newVote: function(){
    const{newVote} = this.election.methods;
    newVote().send({
      from:this.account,
      gas:1000000,
    },function(err,transactionHash){
      if(!err){
        vm.clear();
        alert("新建成功");
      }
      console.log('newVote transactionHash:'+ transactionHash);
      console.log('newVote err:'+ err);
    })
  },
  //判断当前账户是否为Owner
  isOwner:function(){
    const{isOwner} = this.election.methods;
    isOwner().call(function(err, res){
      vm.isCreator = res;
      // console.log('isOwner res:' + res);
      // console.log('isOwner err:' + err);
    })
  },
  //得到候选人数组长度
  getLenOfCan:function(){
    const{getLenOfCan} = this.election.methods;
    getLenOfCan().call(function(err, res){
      console.log('getLenOfCan res:' + res);
      console.log('getLenOfCan err:' + err);
    });
  },
}
window.App = App;

window.addEventListener("load", function() {
  // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
  App.web3 = new Web3(
    new Web3.providers.HttpProvider("http://127.0.0.1:7545")
  );
  App.start();
});

